<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单编号" prop="orderNumber">
        <el-input v-model="queryParams.orderNumber" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择工单类型" clearable>
          <el-option v-for="dict in dict.type.order_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="户号" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择户号" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工单标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入工单标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级" clearable>
          <el-option v-for="dict in dict.type.order_priority" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.order_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['service:workOrder:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['service:workOrder:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service:workOrder:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['service:workOrder:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="orderId" /> -->
      <el-table-column label="工单编号" align="center" prop="orderNumber" />
      <el-table-column label="工单类型" align="center" prop="orderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="户号" align="center" prop="userId" />
      <el-table-column label="工单标题" align="center" prop="title" />
      <el-table-column label="工单描述" align="center" prop="description" />
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_priority" :value="scope.row.priority" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_state" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row)"
            v-hasPermi="['service:workOrder:edit']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="工单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入工单编号" />
        </el-form-item> -->
        <el-form-item label="工单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择工单类型">
            <el-option v-for="dict in dict.type.order_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="户号" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择户号" clearable filterable style="width: 100%">
            <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入工单标题" />
        </el-form-item>
        <el-form-item label="工单描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option v-for="dict in dict.type.order_priority" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.order_state" :key="dict.value"
              :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 审核安装弹出框 -->
    <el-dialog :title="title" :visible.sync="installDialogVisible" width="500px" append-to-body>
      <el-form ref="auditInstallform" :model="auditInstallform" :rules="rules" label-width="80px">
        <el-form-item label="工单编号" prop="orderNumber">
          <el-input v-model="auditInstallform.orderNumber" placeholder="请选择工单编号" clearable filterable
            style="width: 100%" disabled="">
          </el-input>
        </el-form-item>
        <el-form-item label="户号" prop="userId">
          <el-input v-model="auditInstallform.userId" placeholder="请选择户号" clearable filterable style="width: 100%"
            :disabled="true">
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="用户名" prop="userName">
          <el-input v-model="auditInstallform.userName" placeholder="请输入用户名" disabled="" />
        </el-form-item> -->
        <el-form-item label="表号" prop="meterNo">
          <el-input v-model="auditInstallform.meterNo" placeholder="请选择表号" clearable filterable style="width: 100%"
            disabled="">
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="安装人员" prop="installUserId">
          <el-input v-model="auditInstallform.installUserId" placeholder="请选择安装人员" clearable filterable
            style="width: 100%" disabled>
          </el-input>
        </el-form-item> -->

        <el-form-item label="安装日期" prop="installDate">
          <el-date-picker clearable v-model="auditInstallform.installDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择安装日期" disabled="">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="安装类型" prop="installType">
          <el-select v-model="auditInstallform.installType" placeholder="请选择安装类型">
            <el-option v-for="dict in dict.type.install_place" :key="dict.value" :label="dict.label" :value="dict.value"
              disabled=""></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="安装位置" prop="installPlace">
          <el-input v-model="auditInstallform.installPlace" placeholder="请输入安装位置" disabled="" />
        </el-form-item>
        <el-form-item label="安装图片" prop="pic">
          <image-upload v-model="auditInstallform.pic" class="readonly-upload" />
        </el-form-item>
        <el-form-item label="安装描述" prop="installMore">
          <el-input v-model="auditInstallform.installMore" type="textarea" placeholder="请输入内容" disabled="" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="auditInstallform.remark" type="textarea" placeholder="请输入内容" disabled="" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="auditSuccess">通过</el-button>
        <el-button @click="auditFail">打回</el-button>
      </div>
    </el-dialog>


    <!-- 审核维修弹出框 -->
    <el-dialog :title="title" :visible.sync="repairDialogVisible" width="500px" append-to-body>
      <el-form ref="auditRepairform" :model="auditRepairform" :rules="rules" label-width="80px">
        <el-form-item label="工单编号" prop="orderNumber">
          <el-select v-model="auditRepairform.orderNumber" placeholder="请选择工单编号" clearable filterable
            style="width: 100%" disabled>
            <el-option v-for="item in workOrderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="户号" prop="userId">
          <el-select v-model="auditRepairform.userId" placeholder="请选择户号" clearable filterable style="width: 100%"
            disabled>
            <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="表号" prop="meterNo">
          <el-select v-model="auditRepairform.meterNo" placeholder="请选择表号" clearable filterable style="width: 100%"
            disabled>
            <el-option v-for="item in meterOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="维修人员" prop="repairUserId">
          <el-input v-model="auditRepairform.repairUserId" placeholder="请输入维修人员" disabled />
        </el-form-item> -->
        <el-form-item label="维修日期" prop="repairDate">
          <el-date-picker clearable v-model="auditRepairform.repairDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择维修日期" disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维修图片" prop="pic">
          <image-upload v-model="auditRepairform.pic" />
        </el-form-item>
        <el-form-item label="维修描述" prop="repairMore">
          <el-input v-model="auditRepairform.repairMore" type="textarea" placeholder="请输入内容" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="auditRepairform.remark" type="textarea" placeholder="请输入内容" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="auditSuccess">通过</el-button>
        <el-button @click="auditFail">打回</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { listWorkOrder, getWorkOrder, delWorkOrder, addWorkOrder, updateWorkOrder, editByOrderNumber } from "@/api/service/workOrder";
  import { listWaterUser } from "@/api/installation/waterUser";
  import { listUser } from "@/api/system/user";
  import { listRepairInfo, updateInstallInfo } from "@/api/installation/repairInfo";
  import { listInstallInfo, updateRepairInfo } from "@/api/installation/installInfo";

  export default {
    name: "WorkOrderAudit",
    dicts: ['order_state', 'order_priority', 'order_type', 'install_place', 'install_state'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 工单表格数据
        workOrderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        installDialogVisible: false, // 控制安装审核弹窗
        repairDialogVisible: false,  // 控制维修审核弹窗
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderNumber: null,
          orderType: null,
          userId: null,
          title: null,
          priority: null,
          status: null,
        },
        // 查询参数
        queryParamsAudit: {
          pageNum: 1,
          pageSize: 10,
          installUserId: null,
          orderNumber: null,
          companyId: null,
          companyName: null,
          meterNo: null,
          userId: null,
          userName: null,
          installDate: null,
          installType: null,
          installPlace: null,
          installState: null,
          pic: null,
          status,
          installMore: null,
        },
        //更新参数
        queryParamsAuditUpdate: {
          status: null,
          orderNumber: null,
        },
        // 表单参数
        form: {},
        auditInstallform: {
          userId: null,
          userName: null,
          meterNo: null,
          installUserId: null,
          installDate: null,
          installType: null,
          installPlace: '',
          pic: '',
          installMore: '',
          remark: '',
          orderNumber: null  // 确保包含所有API返回的字段
        },
        auditRepairform: {
          userId: null,          // 户号
          meterNo: null,         // 表号
          orderNumber: null,     // 工单编号
          repairUserId: null,    // 维修人员
          repairDate: null,      // 维修日期
          repairState: null,     // 维修状态
          pic: '',               // 维修图片
          repairMore: '',        // 维修描述
          remark: ''             // 备注
        },
        // 表单校验
        rules: {
          orderNumber: [
            { required: true, message: "工单编号不能为空", trigger: "blur" }
          ],
          userId: [
            { required: true, message: "用户ID不能为空", trigger: "blur" }
          ],
          title: [
            { required: true, message: "工单标题不能为空", trigger: "blur" }
          ],
        },
        // 存储用户选项
        waterUserOptions: [],
        // 过滤后的数据
        filteredWaterUserOptions: [],  // 过滤后的数据
        // 存储工单选项
        workOrderOptions: [],
        // 存储施工人员选项
        userOptions: [],
        //施工人员查询条件
        userQueryParams: {
          isWork: 1
        },
        // 存储用户选项
        waterUserOptions: [],
        // 存储表选项
        meterOptions: [],
      };
    },
    created() {
      this.getList();
      this.getWaterUserList();
      this.getUserList();
    },
    methods: {
      /** 查询工单列表 */
      getList() {
        console.log("查询工单审核信息");
        this.loading = true;
        this.queryParams.status = 3;
        listWorkOrder(this.queryParams).then(response => {
          this.workOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询施工人员列表 */
      getUserList() {
        listUser(this.userQueryParams).then(response => {
          this.userOptions = response.rows.map(item => ({
            value: item.userId,
            label: item.userName
          }));
        });
      },
      /** 查询用户列表 */
      getWaterUserList() {
        listWaterUser().then(response => {
          this.waterUserOptions = response.rows.map(item => ({
            value: item.userId,
            label: item.userId
          }));
          this.filteredWaterUserOptions = this.waterUserOptions;
        });
      },
      // 自定义过滤方法（根据输入内容动态匹配）
      filterUserOptions(query) {
        if (query) {
          this.filteredWaterUserOptions = this.waterUserOptions.filter(item =>
            item.value.includes(query) ||  // 匹配户号
            item.label.includes(query)     // 匹配户名
          );
        } else {
          // 输入为空时显示全部选项
          this.filteredWaterUserOptions = this.waterUserOptions;
        }
      },
      //审核通过
      auditSuccess() {
        if (this.auditRepairform.orderNumber) {
          this.queryParamsAuditUpdate.orderNumber = this.auditRepairform.orderNumber;
          // console.log('orderNumber 赋值来源: 维修');
        } else {
          this.queryParamsAuditUpdate.orderNumber = this.auditInstallform.orderNumber;
          // console.log('orderNumber 赋值来源: 安装');
        }
        this.queryParamsAuditUpdate.status = 4;
        editByOrderNumber(this.queryParamsAuditUpdate);
        this.installDialogVisible = false,
          this.repairDialogVisible = false,
          this.open = false;
        this.queryParamsAudit.status = 4;
        this.getList();
      },
      //审核打回
      auditFail() {
        if (this.auditRepairform.orderNumber) {
          this.queryParamsAuditUpdate.orderNumber = this.auditRepairform.orderNumber;
          // console.log('orderNumber 赋值来源: 维修');
        } else {
          this.queryParamsAuditUpdate.orderNumber = this.auditInstallform.orderNumber;
          // console.log('orderNumber 赋值来源: 安装');
        }
        this.queryParamsAuditUpdate.status = 2;
        editByOrderNumber(this.queryParamsAuditUpdate);
        this.installDialogVisible = false,
          this.repairDialogVisible = false,
          this.open = false;
        this.getList();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          orderId: null,
          orderNumber: null,
          orderType: null,
          userId: null,
          title: null,
          description: null,
          priority: null,
          status: null,
          assignedTo: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      resetInstallForm() {
        this.auditInstallform = {
          userId: null,
          userName: null,
          meterNo: null,
          installUserId: null,
          installDate: null,
          installType: null,
          installPlace: '',
          pic: '',
          installMore: '',
          remark: '',
          orderNumber: null
        };
        this.$nextTick(() => {
          this.$refs.auditInstallform?.clearValidate(); // 确保清除验证状态
        });
      },
      resetRepairForm() {
        this.auditRepairform = {
          userId: null,
          meterNo: null,
          orderNumber: null,
          repairUserId: null,
          repairDate: null,
          repairState: null,
          pic: '',
          repairMore: '',
          remark: ''
        };
        this.$nextTick(() => {
          this.$refs.auditRepairform?.clearValidate();
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.orderId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加工单";
        this.getWaterUserList();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const orderId = row.orderId || this.ids
        getWorkOrder(orderId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改工单";
        });
      },
      /** 审核按钮操作 */
      handleAudit(row) {
        this.reset();
        this.queryParamsAudit.orderNumber = row.orderNumber
        const orderType = row.orderType
        if (orderType === 1) {
          // this.resetInstallForm();
          listInstallInfo(this.queryParamsAudit).then(response => {
            this.auditInstallform = response.rows[0];
            this.installDialogVisible = true; // 仅打开安装弹窗
            this.title = "审核报装工单";
          });
        } else {
          // this.resetRepairForm();
          //目前只控制1报装/2维修
          listRepairInfo(this.queryParamsAudit).then(response => {
            this.auditRepairform = response.rows[0];
            this.repairDialogVisible = true;
            this.title = "审核维修工单";
          });
        }
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.orderId != null) {
              updateWorkOrder(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addWorkOrder(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const orderIds = row.orderId || this.ids;
        this.$modal.confirm('是否确认删除工单编号为"' + orderIds + '"的数据项？').then(function () {
          return delWorkOrder(orderIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('service/workOrder/export', {
          ...this.queryParams
        }, `workOrder_${new Date().getTime()}.xlsx`)
      },
      formatUser(row, column, cellValue) {
        // if (cellValue == null) return '未分配';
        // 统一转为字符串比较
        const user = this.userOptions.find(item =>
          String(item.value) === String(cellValue)
        );
        return user.label;
      }
    }
  };
</script>